package org.flashbrighton.as3bots.controllers 
{
	import flash.display.Sprite;
	import org.flashbrighton.as3bots.models.*;
	import org.flashbrighton.as3bots.views.*;
	import Box2D.Common.Math.b2Vec2;

	public class ArenaController
	{
		private var _model:GameModel;
		private var _view:Sprite;
		
		public function ArenaController(model:GameModel, view:GameView) 
		{
			_model = model;
			_view = view;
		}
		
		
		/**
		 * Creates the walls in a clockwise fashion from the top.
		 */
		public function createWalls(arenaWidth:Number):void 
		{
			var halfLength:Number = arenaWidth * 0.5;
			var depth:Number = 0.4;
			var halfDepth:Number = depth * 0.5;
			
			var top:WallModel = new WallModel(_model.physics.addBox(0, 0, halfLength, halfDepth));
			top.body.SetUserData(top);
			_model.addWall(top);
			
			var right:WallModel = new WallModel(_model.physics.addBox(0, 0, halfDepth, halfLength));
			right.body.SetUserData(right);
			_model.addWall(right);
			
			var bottom:WallModel = new WallModel(_model.physics.addBox(0, 0, halfLength, halfDepth));
			bottom.body.SetUserData(bottom);
			_model.addWall(bottom);
			
			var left:WallModel = new WallModel(_model.physics.addBox(0, 0, halfDepth, halfLength));
			left.body.SetUserData(left);
			_model.addWall(left);
			
			// Set positions
			top.body.SetPosition(new b2Vec2(halfLength + depth, halfDepth));
			right.body.SetPosition(new b2Vec2(halfLength * 2 - halfDepth, halfLength + depth));
			bottom.body.SetPosition(new b2Vec2(halfLength - depth, halfLength * 2 - halfDepth));
			left.body.SetPosition(new b2Vec2(halfDepth, halfLength - depth));
		}
		
		
		public function destroyWalls():void 
		{
			while (_model.walls.length > 0)
			{
				_model.removeWall(_model.walls[0]);
			}
		}
		
		
		/**
		 * Positions the bots in a circular fashion.
		 * @param	arenaWidth
		 * @param	arenaHeight
		 */
		public function arrangeBots(arenaWidth:Number, arenaHeight:Number):void
		{
			var halfWidth:Number = arenaWidth * 0.5;
			var halfHeight:Number = arenaHeight * 0.5;
			var n:int = 0;
			var	br:Number;
			var	bx:Number;
			var	by:Number;
			var	brad:Number;
			var	botModel:BotModel;			
			var numBots:int = _model.botList.length;
			
			for each (botModel in _model.botList)
			{
				br = (360 / numBots * n);
				brad = br * Math.PI / 180;
				bx = halfWidth + Math.cos(brad) * (halfWidth * 0.75);
				by = halfHeight + Math.sin(brad) * (halfHeight * 0.75);
				
				botModel.body.SetPosition(new b2Vec2(bx, by));
				botModel.body.SetAngle((br - 180) * Math.PI / 180);
					
				n++;
			}
		}
		
	}

}